package com.ibm.fn.qa.toccata.suite2;

import org.apache.commons.lang.StringUtils;

import com.ibm.fn.qa.toccata.conf.TestData;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;

import junit.framework.TestCase;

/**
 * visit RESTful service and retrieve the template ID of a certain user role.
 *
 * 
 */
public class TestTemplateForUserRole extends TestCase
{

    public void testIndexer() throws Exception
    {
        String userRoleName = "Indexer";
        String expectedTemplateID = "C0A876847F14654D5874ABBFCD6395000000";
        testTemplateOfUserRole(userRoleName, expectedTemplateID);        
    }
    
    public void testReviewer() throws Exception
    {
        String userRoleName = "Reviewer";
        String expectedTemplateID = "C0A876848022598E57A5846D74952A000000";
        testTemplateOfUserRole(userRoleName, expectedTemplateID);        
    }
    
    public void testApprover() throws Exception
    {
        String userRoleName = "Approver";
        String expectedTemplateID = "0927343FC2A831F7B0DC2871D4CA52000000";
        testTemplateOfUserRole(userRoleName, expectedTemplateID);        
    }
    
    private void testTemplateOfUserRole(String userRoleName, String expectedTemplateID) throws Exception
    {
        String templateResourceURL = TestData.templateResourceURL;
        templateResourceURL = StringUtils.replace(templateResourceURL, "%RoleName%", userRoleName);
        System.out.println(templateResourceURL);
        
        WebConversation wc = new WebConversation();
        WebRequest req = new GetMethodWebRequest(templateResourceURL);
        WebResponse resp = wc.getResponse(req);
        
        assertEquals("Return content should be JSON format.", resp.getContentType().toLowerCase(), "application/json");
        assertEquals("Return code should be 200.", resp.getResponseCode(), 200);
        
        boolean isTemplateIdMatch = false;
        String respText = resp.getText().trim();
        //System.out.println("respText: " + respText);
        if((respText.length()>20) && (respText.startsWith("{\"mainTemplateId\":")))
        {
            String currentTemplateID = respText.substring(19, respText.length()-2);
            //System.out.println("currentTemplateID: " + currentTemplateID);
            if(currentTemplateID.equals(expectedTemplateID))
                isTemplateIdMatch = true;
        }
        
        assertTrue("Template ID should match the specified user role.", isTemplateIdMatch);
    }

}
